package com.gict.antifraudback.controller.front.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gict.antifraudback.entity.Config;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.result.ResultView;
import com.gict.antifraudback.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

/**
 * @author ThinkPad
 */
@RestController
@Slf4j
@RequestMapping("/mapi/config")
public class FrontConfigController {

    @Autowired
    private ConfigService configService;

    @GetMapping("/get")
    public ResultView get(@Valid @NotNull String name) {
        Config config = configService.getByName(name);
        if (config == null) {
            throw new MyException("配置不存在");
        }
        return ResultView.ok(config);
    }

    /**
     * 获取多个配置
     * @param names
     * @return
     */
    @PostMapping("/getList")
    public ResultView getList(@RequestBody List<String> names) {
        LambdaQueryWrapper<Config> wrapper = Wrappers.lambdaQuery();
        wrapper.in(Config::getName, names);
        List<Config> configList = configService.list(wrapper);
        if (!CollectionUtils.isEmpty(configList)) {
            HashMap<String, Object> map = new HashMap<>();
            for (Config config : configList) {
                map.put(config.getName(), config.getValue());
            }
            return ResultView.ok(map);
        }
        return ResultView.ok(new HashMap<>());
    }

}
